<template>
  <view class="vip-points">
    <!-- 顶部积分概览 -->
    <view class="header">
      <view class="header-row">
        <text class="title">会员积分</text>
        <view class="rule" @click="rulePopup.open('center')">
          <text>积分说明</text>
        </view>
      </view>
      <view class="total">
        <text class="number">{{ vipPoints.money }}</text>
      </view>
      <view class="summary">
        <view class="summary-item">
          <text class="summary-value">{{ frozenPoints.money }}</text>
          <text class="summary-label">{{ frozenPoints.name }}</text>
        </view>
        <view class="summary-item">
          <text class="summary-value">{{ greenPoints.money }}</text>
          <text class="summary-label">{{ greenPoints.name }}</text>
        </view>
        <view class="summary-item">
          <text class="summary-value">{{ redPoints.money }}</text>
          <text class="summary-label">{{ redPoints.name }}</text>
        </view>
      </view>
    </view>

    <section class="content">
      <!-- 分类切换 -->
      <view class="tabs">
        <view
          v-for="(t, idx) in tabs"
          :key="idx"
          class="tab"
          :class="{ active: activeTab === t.key }"
          @tap="activeTab = t.key"
        >
          {{ t.label }}
        </view>
      </view>

      <!-- 筛选栏 -->
      <!-- <view class="filters">
        <view class="filter-item">
          <text class="filter-title">变动时间</text>
          <picker mode="date" :value="dateRange.start" @change="onStartChange">
            <view class="picker-text">{{ dateRange.start || '请选择' }}</view>
          </picker>
          <text class="split">-</text>
          <picker mode="date" :value="dateRange.end" @change="onEndChange">
            <view class="picker-text">{{ dateRange.end || '请选择' }}</view>
          </picker>
        </view>
      </view> -->

      <!-- 列表 -->
      <view class="list">
        <view
          v-for="item in orderList"
          :key="item.id"
          class="list-item"
          @click="viewDetail(item.selfOrder)"
        >
          <view class="store">{{ item.goodsName }}</view>
          <view class="row">
            <text class="label">订单编号</text>
            <text class="value">{{ item.selfOrder.orderTradeId }}</text>
          </view>
          <view class="row">
            <text class="label">订单金额</text>
            <text class="value">￥{{ item.selfOrder.tradeMoney }}</text>
          </view>
          <view class="row">
            <text class="label">变动时间</text>
            <text class="value">{{
              formatDate(item.selfOrder.tradeTime)
            }}</text>
          </view>
          <view class="foot">
            <text
              class="points"
              :class="{
                inc: item.selfOrder.gainOfferIntegral > 0,
                dec: item.selfOrder.gainOfferIntegral < 0,
              }"
            >
              {{
                item.selfOrder.gainOfferIntegral > 0
                  ? "+" + item.selfOrder.gainOfferIntegral
                  : item.selfOrder.gainOfferIntegral
              }}
            </text>
            <view class="tag">{{ item.pluralName }}</view>
          </view>
        </view>
      </view>
    </section>
    <uni-popup ref="rulePopup" type="center">
      <view class="rule-popup">
        <view class="rule-title">积分说明</view>
        <view class="rule-item">
          <text class="rule-item-title">冻结积分</text>
          <text class="rule-item-desc"
            >用户消费后获得的积分以防产生退款问题，按照确认收货后七日以后解冻，七天一个周期进行返还</text
          >
        </view>
        <view class="rule-item">
          <text class="rule-item-title">绿色积分</text>
          <text class="rule-item-desc">会员消费等行为获得的积分</text>
        </view>
        <view class="rule-item">
          <text class="rule-item-title">红色积分</text>
          <text class="rule-item-desc"
            >创客分享用户消费获得的一个加速积分，若分享的用户没有消费则按照正常周期，七天返还一次</text
          >
        </view>
        <button class="rule-btn" @click="rulePopup.close()">知道了</button>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, getCurrentInstance } from "vue";
import { onShow, onReachBottom } from "@dcloudio/uni-app";
import { formatDate } from "@/utils/filters";
import rsa from "@/utils/rsa";
import { encryptApi } from "@/api/index";

const userId = ref(uni.getStorageSync("userInfo").userId);

// Refs
const rulePopup = ref(null);

// Data
const summary = ref({ share: 0, customer: 0, business: 0 });
const tabs = ref([
  { key: "vip", label: "会员积分" },
  // { key: 'share', label: '分享积分' },
  // { key: 'customer', label: '潮客积分' },
  // { key: 'biz', label: '业务积分' }
]);
const activeTab = ref("vip");
const dateRange = ref({ start: "", end: "" });

const vipPoints = ref({});
const greenPoints = ref({});
const redPoints = ref({});
const frozenPoints = ref({});

// 分页相关参数
const page = ref(1);
const limit = ref(10);
const allTotal = ref(0);
const status = ref("loading"); // loading, noMore
const loading = ref(false);
const orderList = ref([]);

// Methods
const getData = () => {
  encryptApi({
    a_m: "cyBerFreeze_anb",
    a_d: rsa.encrypt({ uid: userId.value }, true),
  }).then((res) => {
    // Original code set this.freeze = res.data but it wasn't defined in data
    // Keeping basic structure
  });

  encryptApi({
    a_d: rsa.encrypt({ u: userId.value }, true),
    a_m: "da_allMoney",
  }).then((res) => {
    if (res.code == 2000) {
      // 绿色积分
      greenPoints.value = res.data.find((item) => item.id == 4) || {};
      // 红色积分
      redPoints.value = res.data.find((item) => item.id == 3) || {};
      // 冻结积分
      frozenPoints.value = res.data.find((item) => item.id == 5) || {};

      vipPoints.value = res.data.find((item) => item.id == 7) || {};
    }
  });
};

// 获取订单列表
const loadData = (isLoadMore = false) => {
  if (loading.value) return;

  if (!isLoadMore) {
    page.value = 1;
    // orderList.value = []; // Original code cleared goodsList but used orderList
  }
  loading.value = true;
  encryptApi({
    a_m: "so_soList",
    a_d: rsa.encrypt(
      {
        limit: 10,
        offset: page.value,
        tradeStatus: -1,
        userId: userId.value,
      },
      true
    ),
  }).then((res) => {
    loading.value = false;
    if (res.data) {
      if (isLoadMore) {
        orderList.value = [...orderList.value, ...res.data];
      } else {
        orderList.value = res.data;
      }
      allTotal.value = res.data.total || 0;

      // 判断是否还有更多数据
      if (orderList.value.length >= allTotal.value) {
        status.value = "noMore";
      } else {
        status.value = "loading";
      }
    }
  });
};

const scrollLower = () => {
  if (orderList.value.length >= allTotal.value) {
    status.value = "noMore";
    uni.showToast({
      title: "当前已加载完毕",
      icon: "none",
    });
    return;
  } else {
    status.value = "loading";
    page.value++;
    loadData(true);
  }
};

// 查看订单详情
const viewDetail = (item) => {
  console.log("查看详情:", item);
  uni.navigateTo({
    url: `/pages/vipPoints/vipPointsDetail?orderTradeId=${item.orderTradeId}`,
  });
};

const onStartChange = (e) => {
  dateRange.value.start = e.detail.value;
};

const onEndChange = (e) => {
  dateRange.value.end = e.detail.value;
};

// Lifecycle
onShow(() => {
  loadData();
  getData();
});

onReachBottom(() => {
  scrollLower();
});
</script>

<style scoped lang="scss">
.vip-points {
  height: calc(100vh - 44px);
  background: linear-gradient(180deg, #35d0a1 0%, #2cc389 80%);
  display: flex;
  flex-direction: column;

  .header {
    padding: 24rpx 24rpx 32rpx;
    color: #fff;
    border-bottom-left-radius: 24rpx;
    border-bottom-right-radius: 24rpx;

    .header-row {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .title {
        font-size: 32rpx;
        font-weight: 600;
      }

      .rule {
        background-color: rgba(255, 255, 255, 0.2);
        border-radius: 24rpx;
        padding: 10rpx 20rpx;
        font-size: 24rpx;
      }
    }

    .total {
      margin-top: 20rpx;

      .number {
        font-size: 60rpx;
        font-weight: 700;
      }
    }

    .summary {
      margin-top: 30rpx;
      display: flex;
      gap: 20rpx;
      background-color: rgba(255, 255, 255, 0.18);
      padding: 20rpx;
      border-radius: 16rpx;

      .summary-item {
        flex: 1;
        text-align: center;

        .summary-value {
          font-size: 32rpx;
          font-weight: 600;
        }

        .summary-label {
          display: block;
          margin-top: 6rpx;
          font-size: 22rpx;
        }
      }
    }
  }

  .content {
    background-color: #f7f7f7;
    border-radius: 24rpx 24rpx 0 0;
    flex: 1;

    .tabs {
      margin: 24rpx;
      display: flex;
      overflow: hidden;

      .tab {
        width: 25%;
        text-align: center;
        padding: 20rpx 0;
        font-size: 26rpx;
        color: #777;
        position: relative;

        &.active {
          color: #27b37d;
          font-weight: 600;

          &::after {
            content: "";
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 60rpx;
            height: 6rpx;
            background-color: #27b37d;
            border-radius: 2rpx;
          }
        }
      }
    }

    .filters {
      margin: 0 24rpx;
      background-color: #fff;
      border-radius: 16rpx;
      padding: 16rpx 20rpx;

      .filter-item {
        display: flex;
        align-items: center;

        .filter-title {
          width: 160rpx;
          color: #333;
          font-size: 26rpx;
        }

        .picker-text {
          padding: 10rpx 16rpx;
          background-color: #f5f6fa;
          border-radius: 10rpx;
          color: #666;
          font-size: 24rpx;
        }

        .split {
          margin: 0 16rpx;
          color: #999;
        }
      }
    }

    .list {
      padding: 24rpx;
      margin: 24rpx;
      overflow: auto;
      background-color: #fff;
      border-radius: 16rpx;

      .list-item {
        margin-bottom: 18rpx;
        padding-bottom: 18rpx;
        border-bottom: 1px solid #f5f6fa;

        &:last-child {
          margin-bottom: 0;
          padding-bottom: 0;
          border-bottom: none;
        }

        .store {
          font-size: 28rpx;
          font-weight: 600;
          margin-bottom: 12rpx;
        }

        .row {
          display: flex;
          justify-content: space-between;
          padding: 15rpx 0;

          .label {
            color: #666;
            font-size: 24rpx;
          }

          .value {
            color: #333;
            font-size: 24rpx;
          }
        }

        .foot {
          margin-top: 15rpx;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .points {
            font-size: 28rpx;
            font-weight: 700;

            &.inc {
              color: #2ac28a;
            }

            &.dec {
              color: #e54d42;
            }
          }

          .tag {
            background-color: #2ac28a;
            color: #fff;
            font-size: 22rpx;
            padding: 12rpx 16rpx;
            border-radius: 0 20rpx 0 20rpx;
          }
        }
      }
    }
  }
}

.rule-popup {
  width: 80vw;
  max-width: 640rpx;
  background: #ffffff;
  border-radius: 20rpx;
  padding: 24rpx;
  color: #333;
}

.rule-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #1f1f1f;
  margin-bottom: 16rpx;
}

.rule-item {
  margin-top: 12rpx;
}

.rule-item-title {
  font-size: 26rpx;
  font-weight: 600;
  color: #333;
}

.rule-item-desc {
  font-size: 24rpx;
  color: #666;
  margin-top: 8rpx;
  line-height: 1.6;
}

.rule-btn {
  margin-top: 24rpx;
  width: 100%;
  height: 64rpx;
  line-height: 64rpx;
  text-align: center;
  color: #ffffff;
  background: #2ac28a;
  border-radius: 12rpx;
}
</style>
